package cn.ococci.dm.WiFi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 * Created by Cyan on 15/9/10.
 * 网络状态的监听
 */
public class NetWorkStateBroadcastReceiver extends BroadcastReceiver {

    public static final String ACTION_NETWORK_STATUS_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
    public static final String ACTION_NETWORK_STATUS_CHANGE_ETHERNET = "android.net.ethernet.ETHERNET_STATE_CHANGED";
    public static final String ACTION_NETWORK_STATUS = "android.net.ethernet.STATE_CHANGE";

    public interface NetWorkStateListener {
        /**
         * Wifi连接
         * @param BSSid
         */
        void onNetWorkWithWifConnected(String BSSid);


        /**
         * 没有网络连接
         */
        void onNetworkDisconnected();


    }
    private NetWorkStateListener listener;
    private ConnectivityManager connManager;

    public NetWorkStateBroadcastReceiver(NetWorkStateListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if(isNetWork(intent)){   // 根据比较Action进入网络状态
            connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = connManager.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isAvailable()){  //网络可用
                netWorkState(context);
            }else{
                this.listener.onNetworkDisconnected();
            }
        }

    }

    public void netWorkState(Context context) {
        NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();// 获取Wifi网络连接状态
        if (NetworkInfo.State.CONNECTED == state) { // 判断是否正在使用WIFI网络
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            WifiInfo wifiInfo= wifiManager.getConnectionInfo();
            if(wifiInfo != null){
                this.listener.onNetWorkWithWifConnected(wifiInfo.getBSSID());
            }


        }else {

            this.listener.onNetworkDisconnected();
        }

    }


    /**
     * 获取当前Intent的Action 确定是否是网络操作
     * @param intent
     * @return
     */
    private boolean isNetWork(Intent intent){
        return  intent.getAction().equals("android.net.ethernet.ETHERNET_STATE_CHANGED")||
                intent.getAction().equals("android.net.ethernet.STATE_CHANGE")||
                intent.getAction().equals(ACTION_NETWORK_STATUS_CHANGE); //这个是网络开关
    }


}
